package cn.stylefeng.guns.modular.statistics.controller;

import cn.hutool.core.date.DateTime;
import cn.stylefeng.guns.core.common.annotion.BussinessLog;
import cn.stylefeng.guns.core.common.annotion.Permission;
import cn.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import cn.stylefeng.guns.core.common.constant.factory.PageFactory;
import cn.stylefeng.guns.core.common.page.PageInfoBT;
import cn.stylefeng.guns.core.log.LogObjectHolder;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.modular.account.service.IAccountService;
import cn.stylefeng.guns.modular.budget.service.IBudgetService;
import cn.stylefeng.guns.modular.classification.service.IClassificationService;
import cn.stylefeng.guns.modular.family.service.IFamilyService;
import cn.stylefeng.guns.modular.familynum.service.IFamilynumService;
import cn.stylefeng.guns.modular.items.service.IItemsService;
import cn.stylefeng.guns.modular.system.model.*;
import cn.stylefeng.guns.modular.system.service.IUserService;
import cn.stylefeng.guns.modular.system.warpper.FamilyWarpper;
import cn.stylefeng.guns.modular.system.warpper.ItemsWarpper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.models.auth.In;
import javafx.util.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

/**
 * 家庭表控制器
 *
 * @author fengshuonan
 * @Date 2021-04-12 10:48:11
 */
@Controller
@RequestMapping("/statistics")
public class StatisticsController extends BaseController {

    private String PREFIX = "/statistics/statistics/";

    @Autowired
    private IFamilyService familyService;

    @Autowired
    private IAccountService accountService;

    @Autowired
    private IClassificationService classificationService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IFamilynumService familynumService;

    @Autowired
    private IItemsService itemsService;

    @Autowired
    private IBudgetService budgetService;

    /**
     * 跳转到个人统计表
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "statistics.html";
    }

    /**
     * 跳转到家庭统计表
     */
    @RequestMapping("/statisticsfamily")
    public String jump() {
        return PREFIX + "statisticsfamily.html";
    }

    /**
     * 跳转到预算统计表
     */
    @RequestMapping("/statisticsbudget")
    public String jump2(Model model) {

        Integer userid=ShiroKit.getUser().getId();
        EntityWrapper<Budget> budgetEntityWrapper=new EntityWrapper<>();
        budgetEntityWrapper.eq("updateid",userid);

        Calendar cal = Calendar.getInstance();
        Integer year = cal.get(Calendar.YEAR);//获取年
        Integer month = cal.get(Calendar.MONTH )+1;//获取月

        String x=year.toString()+"-";
        if(month<10){
            x=x+"0";
        }
        x=x+month.toString();
        budgetEntityWrapper.like("createtime",x);

        List<Budget> budgetList=budgetService.selectList(budgetEntityWrapper);
        BigDecimal bigDecima=BigDecimal.valueOf(0);
        for(int i=0;i<budgetList.size();i++){
            bigDecima=bigDecima.add(budgetList.get(i).getBudgetmoney());
        }
        model.addAttribute("bigDecima",bigDecima);
        model.addAttribute("num",budgetList.size());

        return PREFIX + "statisticsbudget.html";
    }

    /**
     * 显示
     */
    //个人 消费占比
    @RequestMapping(value = "/show1")
    @ResponseBody
    public Map<String, BigDecimal> show1(@RequestParam("x") String x){
//
//        EntityWrapper<Account> accountEntityWrapper=new EntityWrapper<>();
//        List<Account> accountList=accountService.selectList(accountEntityWrapper);
//
//        System.out.println("*********");
//        System.out.println(toJson(accountList));
//        return accountList;


        Integer YEAR=Integer.valueOf(x.substring(0,4).toString());
        Integer MONTH=Integer.valueOf(x.substring(5,7).toString());

        //个人账单
        Integer userid=ShiroKit.getUser().getId(); //用户id
        List<Items> itemsList=getPersonItems(userid); //个人账单

        return getMap(itemsList,YEAR,MONTH);
    }

    //家庭消费占比 家庭饼状图
    @RequestMapping(value = "/show3")
    @ResponseBody
    public Map<String, BigDecimal> show3(@RequestParam("x") String x){


        Integer YEAR=Integer.valueOf(x.substring(0,4).toString());
        Integer MONTH=Integer.valueOf(x.substring(5,7).toString());


        Integer userid=ShiroKit.getUser().getId(); //用户id
//        Integer familyid=userService.selectById(userid).getVersion();//当前用户的家庭id
        Integer familyid=getFamilyid(userid);//当前用户的家庭id

        List<Items> itemsList=new LinkedList<>();
        if(familyid!=-1){
            itemsList=getFamliyItems(userid);
        }

        return getMap(itemsList,YEAR,MONTH);
    }

    //个人折线图
    @RequestMapping(value = "/show2")
    @ResponseBody
    public List<Store> show2(@RequestParam("y") Integer y){

        Integer YEAR=y;

        //个人账单
        Integer userid=ShiroKit.getUser().getId(); //用户id
        List<Items> itemsList=getPersonItems(userid); //个人账单

        return getStore(itemsList,YEAR);
    }

    //家庭折线图
    @RequestMapping(value = "/show4")
    @ResponseBody
    public List<Store> show4(@RequestParam("y") Integer y){


        Integer YEAR=y;

        EntityWrapper<Items> itemsEntityWrapper=new EntityWrapper<>();
        Integer userid=ShiroKit.getUser().getId(); //用户id
//        Integer familyid=userService.selectById(userid).getVersion();//当前用户的家庭id
        Integer familyid=getFamilyid(userid);//当前用户的家庭id

        List<Items> itemsList=new LinkedList<>();
        if(familyid!=-1){
            itemsList=getFamliyItems(userid);
        }

        return getStore(itemsList,YEAR);
    }

    //预算使用情况
    @RequestMapping(value = "/show5")
    @ResponseBody
    public List<Store> show5(@RequestParam("x") String x){


        Integer YEAR=Integer.valueOf(x.substring(0,4).toString());
        Integer MONTH=Integer.valueOf(x.substring(5,7).toString());

        //个人账单
        Integer userid=ShiroKit.getUser().getId(); //用户id
        List<Items> itemsList=getPersonItems(userid); //个人账单

        Map<String,BigDecimal> mm=getMap(itemsList,YEAR,MONTH);

        //个人预算
        EntityWrapper<Budget> budgetEntityWrapper=new EntityWrapper<>();
        budgetEntityWrapper.eq("updateid",userid);
        budgetEntityWrapper.like("createtime",x);
        List<Budget> budgetList=budgetService.selectList(budgetEntityWrapper);


        List<Store> storeList=new LinkedList<>();

        for(int i=0;i<budgetList.size();i++){
            String budgetKind=budgetList.get(i).getBudgetkind();//预算类型
            String budgetName=ConstantFactory.me().getKindName(budgetKind);//预算名称
            BigDecimal budgetMoney=budgetList.get(i).getBudgetmoney();//预算金额

            Store store =new Store();
            store.setV1(budgetName);//预算名称
            store.setBig1(budgetMoney);//预算金额

            if(mm.get(budgetName)!=null){
                store.setBig2(mm.get(budgetName)); //实际消费金额
            }
            else {
                store.setBig2(new BigDecimal(0));//实际消费金额
            }

            storeList.add(store);
        }

        return storeList;
    }

    //个人 预算占比
    @RequestMapping(value = "/show6")
    @ResponseBody
    public List<Store> show6(@RequestParam("x") String x){


        Integer YEAR=Integer.valueOf(x.substring(0,4).toString());
        Integer MONTH=Integer.valueOf(x.substring(5,7).toString());

        //个人预算
        Integer userid=ShiroKit.getUser().getId(); //用户id
        EntityWrapper<Budget> budgetEntityWrapper=new EntityWrapper<>();
        budgetEntityWrapper.eq("updateid",userid);
        List<Budget> budgetList=budgetService.selectList(budgetEntityWrapper);


        List<Store> storeList=new LinkedList<>();

        for(int i=0;i<budgetList.size();i++){
            Calendar c = Calendar.getInstance();
            c.setTime(budgetList.get(i).getCreatetime());
            int year = c.get(Calendar.YEAR);
            int month=c.get(Calendar.MONTH)+1;

            if(year==YEAR&&month==MONTH){
                Store store=new Store();
                String budgetKind=budgetList.get(i).getBudgetkind();
                String budgetName=ConstantFactory.me().getKindName(budgetKind);//预算类型
                BigDecimal budgetMoney=budgetList.get(i).getBudgetmoney();//预算金额

                store.setV1(budgetName);
                store.setBig1(budgetMoney);

                storeList.add(store);
            }

        }

        return storeList;

    }


    //此家庭中一定人数>=1
    public List<Items> getFamliyItems(Integer userid){


//        Integer familyid=userService.selectById(userid).getVersion();//当前用户的家庭id
        Integer familyid=getFamilyid(userid);//当前用户的家庭id

        EntityWrapper<Familynum> familynumEntityWrapper=new EntityWrapper<>();
        familynumEntityWrapper.eq("familyid",familyid);
        List<Familynum> familynumList=familynumService.selectList(familynumEntityWrapper); //筛选出同一个家庭的成员列表

        List<Integer> useridlist=new LinkedList<>();  //用户userid
        for(int i=0;i<familynumList.size();i++){
            Familynum f=familynumList.get(i);
            useridlist.add(f.getFamilyuserid());
        }

        EntityWrapper<Account> accountEntityWrapper=new EntityWrapper<>();
        accountEntityWrapper.in("userid",useridlist);
        List<Account> accountList=accountService.selectList(accountEntityWrapper); //家庭账户

        List<Integer> accountidlist=new LinkedList<>();//家庭中所有成员的账户id
        for(int i=0;i<accountList.size();i++){
            Account account=accountList.get(i);
            accountidlist.add(account.getId());
        }

        EntityWrapper<Items> itemsEntityWrapper=new EntityWrapper<>();

        if(accountidlist.size()==0){
            itemsEntityWrapper.eq("accountid",-1);
        }
        else{
            itemsEntityWrapper.in("accountid",accountidlist);
        }

        List<Items> itemsList=itemsService.selectList(itemsEntityWrapper); //家庭账单

        return itemsList;
    }

    public List<Items> getPersonItems(Integer userid){

        EntityWrapper<Account> accountEntityWrapper=new EntityWrapper<>();
        accountEntityWrapper.eq("userid",userid);
        List<Account> accountList=accountService.selectList(accountEntityWrapper);//本人的所有账户

        List<Integer> accountidlist=new LinkedList<>();//本人的账户id
        for(int i=0;i<accountList.size();i++){
            Account account=accountList.get(i);
            accountidlist.add(account.getId());
        }

        EntityWrapper<Items> itemsEntityWrapper=new EntityWrapper<>();

        if(accountidlist.size()==0){
            itemsEntityWrapper.eq("accountid",-1);
        }
        else{
            itemsEntityWrapper.in("accountid",accountidlist);
        }

        List<Items> itemsList=itemsService.selectList(itemsEntityWrapper); //个人账单

        return itemsList;
    }

    //show2 show4 用
    public List<Store> getStore(List<Items> itemsList ,Integer YEAR){
        BigDecimal [] zclist=new BigDecimal[13];
        BigDecimal [] srlist=new BigDecimal[13];

        for(int i=0;i<itemsList.size();i++){

            Items items=itemsList.get(i);
            String paykind=items.getPaykind();//支出类型
            BigDecimal money=items.getPay();//支出金额
            String pcode=ConstantFactory.me().getFatherCode(paykind);//支出还是收入

            //获取年份
            Calendar c = Calendar.getInstance();
            c.setTime(items.getPaytime());
            int year = c.get(Calendar.YEAR);
            int month=c.get(Calendar.MONTH)+1;
            if(YEAR==year){
                if(pcode.equals("zclx")){//支出类型
                    if(zclist[month]==null){
                        zclist[month]=money;
                    }
                    else{

                        zclist[month]=zclist[month].add(money);
                    }

                }
                else if(pcode.equals("srlx")){
                    if(srlist[month]==null){
                        srlist[month]=money;
                    }
                    else{
                        srlist[month]=srlist[month].add(money);
                    }

                }
            }


        }


        List<Store> storeList=new LinkedList<>();

        for(int i=1;i<13;i++){

            Store store=new Store();
            store.setN1(i);
//            if(zclist[i]==null&&srlist[i]==null) {
//                store.setN2(0);
//                store.setN3(0);
//            }
//            else if(zclist[i]==null){
//                store.setN2(0);  //支出
//                store.setN3(Integer.valueOf(srlist[i].toString()));//收入
//            }
//            else if(srlist[i]==null){
//                store.setN3(0);
//                store.setN2(Integer.valueOf(zclist[i].toString()));
//            }
//            else{
//                store.setN2(Integer.valueOf(zclist[i].toString()));
//                store.setN3(Integer.valueOf(srlist[i].toString()));
//            }

            if(zclist[i]==null&&srlist[i]==null) {
                store.setBig2(new BigDecimal(0));
                store.setBig3(new BigDecimal(0));
            }
            else if(zclist[i]==null){
                store.setBig2(new BigDecimal(0));  //支出
                store.setBig3(srlist[i]);//收入
            }
            else if(srlist[i]==null){
                store.setBig3(new BigDecimal(0));
                store.setBig2(zclist[i]);
            }
            else{
                store.setBig2(zclist[i]);
                store.setBig3(srlist[i]);
            }
            storeList.add(store);
        }



        return storeList;

    }

    //show1 show3 用
    public Map<String,BigDecimal> getMap(List<Items> itemsList,Integer YEAR,Integer MONTH){
        Map<String,BigDecimal> mm= new HashMap<>();
        EntityWrapper<Classification> classificationEntityWrapper=new EntityWrapper<>();

        for(int i=0;i<itemsList.size();i++){
            String paykind=itemsList.get(i).getPaykind();//支出类型
            BigDecimal pay=itemsList.get(i).getPay();//支出金额

            //获取年份
            Calendar c = Calendar.getInstance();
            c.setTime(itemsList.get(i).getPaytime());
            int year = c.get(Calendar.YEAR);
            int month=c.get(Calendar.MONTH)+1;

            if(YEAR==year&&MONTH==month){
                String pcode=ConstantFactory.me().getFatherCode(paykind);
                if(pcode.equals("zclx")){
                    if(mm.get(ConstantFactory.me().getKindName(paykind))!=null){
                        pay=pay.add(mm.get(ConstantFactory.me().getKindName(paykind)));
                    }

                    mm.put(ConstantFactory.me().getKindName(paykind),pay);
                }
            }
        }
        for(String key : mm.keySet()){
            BigDecimal value = mm.get(key);

        }

        return mm;
    }

    public Integer getFamilyid(Integer userid){
        EntityWrapper<Familynum> familynumEntityWrapper1=new EntityWrapper<>();
        familynumEntityWrapper1.eq("familyuserid",userid);
        Familynum familynum=familynumService.selectOne(familynumEntityWrapper1);


        //判断是否为空时不能够用 .equals(null)
        if(familynum==null){
            return -1;
        }
        else{
            return familynum.getFamilyid();
        }
    }
}
